package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import com.teach.javafxclient.util.HttpUtil;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import kong.unirest.Unirest;
import kong.unirest.json.JSONArray;
import kong.unirest.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Liang Jianlin
 * @date 2024-05-14 22:42
 */
public class StudentSelectController {
    public VBox studentContainer;
    public Button confirm;
    public Label output;
    private Map<String,Long> studentMap = new HashMap<>();
    public void initialize() throws IOException {
        JSONArray res = HttpUtil.get(Globalvar.baseUrl+"/api/students")
                .header("Accept", "application/json")
                .asJson()
                .getBody()
                .getArray();
        for (int i = 0; i < res.length(); i++) {
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/mini-student-item.fxml"));
            Parent root = fxmlLoader.load();
            MiniStudentItemController MSIC = fxmlLoader.getController();
            MSIC.name.setText((String) ((JSONObject)res.get(i)).get("name"));
            MSIC.id.setText(String.valueOf(((JSONObject)res.get(i)).get("studentId")));
            int finalI = i;
            int finalI1 = i;
            MSIC.main.setOnMouseClicked(e->{
                System.out.println(MSIC.choose.isManaged());
                MSIC.choose.setManaged(!MSIC.choose.isManaged());
                MSIC.choose.setVisible(!MSIC.choose.isVisible());
                if(MSIC.choose.isVisible()){
                    studentMap.put((String) ((JSONObject)res.get(finalI)).get("name"),(Long)((JSONObject)res.get(finalI1)).get("studentId"));
                }else{
                    studentMap.remove((String) ((JSONObject)res.get(finalI)).get("name"));
                }
            });
            studentContainer.getChildren().add(root);
        }
    }
    public JSONArray getSelectedStudentList(){
        JSONArray studentList = new JSONArray();
        for (Map.Entry<String, Long> entry : studentMap.entrySet()) {
            studentList.put(entry.getValue());
        }
        return studentList;
    }
}
